﻿using System;
using System.Drawing;
using System.Threading.Tasks;
using System.Windows.Forms;
using HZH_Controls.Forms;
using NovelDownload.Common;

namespace NovelDownload
{
    public partial class FrmMain : Form
    {
        public FrmMain()
        {
            InitializeComponent();
        }

        MhtNovelSite mhtNovel = new MhtNovelSite("棉花糖", "https://www.mhtxs.la/", "https://www.mhtxs.la/search.php", "https://txt.mhtxs.la/");
        XswNovelSite xswNovel = new XswNovelSite("炫书网", "https://www.ibiquta.com/", "https://www.ibiquta.com/search.html", "https://txt.ibiquta.com/home/down/txt/id/");
        WsNovelSite wsNovel = new WsNovelSite("文桑", "http://www.wlwx.org", "http://www.wlwx.org/home/search", "http://txt.wlwx.org/modules/article/txtarticle.php?id=");


        /// <summary>
        /// 搜索按钮被单击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSearch_Click(object sender, EventArgs e)
        {
            dgvSearchResult.Rows.Clear();
            string searchKeyWord = txtSearch.Text.Trim();


            //棉花糖
            var mhtAwaiter = mhtNovel.SearchNovel(searchKeyWord).GetAwaiter();
            mhtAwaiter.OnCompleted(() => UiOperate.SearchResultAddData(this, dgvSearchResult, mhtNovel.SiteName, mhtAwaiter.GetResult()));

            // 炫书网搜索
            var xswAwaiter = xswNovel.SearchNovel(searchKeyWord).GetAwaiter();
            xswAwaiter.OnCompleted(() => UiOperate.SearchResultAddData(this, dgvSearchResult, xswNovel.SiteName, xswAwaiter.GetResult()));

            // 文桑小说搜索
            var wsAwaiter = wsNovel.SearchNovel(searchKeyWord).GetAwaiter();
            wsAwaiter.OnCompleted(() => UiOperate.SearchResultAddData(this, dgvSearchResult, wsNovel.SiteName, wsAwaiter.GetResult()));

        }


        /// <summary>
        /// 编辑框回车
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtSearch_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                this.btnSearch_Click(sender, e);
            }
            return;
        }


        /// <summary>
        /// 搜索结果列表中按钮被单击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvSearchResult_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // 获取当前点击的小说链接
            string novelLink = dgvSearchResult.Rows[e.RowIndex].Cells[1].Tag.ToString();
            string novelName = dgvSearchResult.Rows[e.RowIndex].Cells[1].Value.ToString();

            // 获取点击的单元格
            DataGridViewCell cell = dgvSearchResult.Rows[e.RowIndex].Cells[e.ColumnIndex];
            // 单元格的值
            string cellVal = cell.FormattedValue.ToString();
            switch (cellVal)
            {
                case "阅读":
                    dgvChapterList.Visible = true;
                    tabControl1.SelectedIndex = 1;
                    // 棉花糖
                    if (novelLink.Contains(mhtNovel.SiteHomeUrl))
                    {
                        var mhtAwaiter = mhtNovel.GetAllChapterInfo(novelLink).GetAwaiter();
                        try
                        {
                            mhtAwaiter.OnCompleted(() => UiOperate.ChapterListAddData(this, dgvChapterList, mhtAwaiter.GetResult()));
                        }
                        catch (Exception ex)
                        {
                            FrmTips.ShowTipsError(this, ex.Message);
                        }
                    }

                    // 炫书网
                    if (novelLink.Contains(xswNovel.SiteHomeUrl))
                    {
                        var xswAwaiter = xswNovel.GetAllChapterInfo(novelLink).GetAwaiter();
                        try
                        {
                            xswAwaiter.OnCompleted(() => UiOperate.ChapterListAddData(this, dgvChapterList, xswAwaiter.GetResult()));
                        }
                        catch (Exception ex)
                        {
                            FrmTips.ShowTipsError(this, ex.Message);
                        }
                    }

                    // 文桑
                    if (novelLink.Contains(wsNovel.SiteHomeUrl))
                    {
                        var wsAwaiter = wsNovel.GetAllChapterInfo(novelLink).GetAwaiter();
                        try
                        {
                            wsAwaiter.OnCompleted(() => UiOperate.ChapterListAddData(this, dgvChapterList, wsAwaiter.GetResult()));
                        }
                        catch (Exception ex)
                        {
                            FrmTips.ShowTipsError(this, ex.Message);
                        }
                    }

                    break;

                case "下载":
                    // 棉花糖
                    if (novelLink.Contains(mhtNovel.SiteHomeUrl))
                    {
                        var novelIdTemp = novelLink.TrimEnd('/');
                        var novelId = novelIdTemp.Substring(novelIdTemp.LastIndexOf("/") + 1);
                        var downloadUrl = $"{mhtNovel.BaseDownloadUrl}{novelId}/{novelName}.txt";
                        var fileName = $"{novelName}.txt";

                        FolderBrowserDialog folder = new FolderBrowserDialog();
                        if (folder.ShowDialog() == DialogResult.OK)
                        {
                            string downloadPath = folder.SelectedPath;
                            //FrmTips.ShowTipsInfo(this, "开始下载");
                            FrmTips.ShowTips(this, "开始下载！", 1000, false, ContentAlignment.MiddleCenter, null, TipsSizeMode.Large, null, TipsState.Info);
                            var downAwaiter = wsNovel.DownloadNovel(downloadPath, downloadUrl, fileName).GetAwaiter();
                            downAwaiter.OnCompleted(() => {
                                //FrmTips.ShowTipsSuccess(this, "下载完成");
                                FrmTips.ShowTips(this, "下载完成！", 1000, false, ContentAlignment.MiddleCenter, null, TipsSizeMode.Large, null, TipsState.Success);
                            });
                        }
                    }

                    // 炫书网
                    if (novelLink.Contains(xswNovel.SiteHomeUrl))
                    {
                        var novelId = novelLink.Substring(novelLink.LastIndexOf("/") + 1).Replace(".html", "");
                        var downloadUrl = $"{xswNovel.BaseDownloadUrl}{novelId}";
                        var fileName = $"{novelName}.txt";

                        FolderBrowserDialog folder = new FolderBrowserDialog();
                        if (folder.ShowDialog() == DialogResult.OK)
                        {
                            string downloadPath = folder.SelectedPath;
                            FrmTips.ShowTips(this, "开始下载！", 1000, false, ContentAlignment.MiddleCenter, null, TipsSizeMode.Large, null, TipsState.Info);
                            var downAwaiter = wsNovel.DownloadNovel(downloadPath, downloadUrl, fileName).GetAwaiter();
                            downAwaiter.OnCompleted(() => {
                                FrmTips.ShowTips(this, "下载完成！", 1000, false, ContentAlignment.MiddleCenter, null, TipsSizeMode.Large, null, TipsState.Success);
                            });
                        }
                    }


                    // 文桑
                    if (novelLink.Contains(wsNovel.SiteHomeUrl))
                    {
                        var temp = novelLink.TrimEnd('/');
                        var id = temp.Substring(temp.LastIndexOf("/") + 1);
                        var downloadUrl = $"{wsNovel.BaseDownloadUrl}{id}";
                        var fileName = $"{novelName}.txt";

                        FolderBrowserDialog folder = new FolderBrowserDialog();
                        if (folder.ShowDialog() == DialogResult.OK)
                        {
                            string downloadPath = folder.SelectedPath;
                            FrmTips.ShowTips(this, "开始下载！", 1000, false, ContentAlignment.MiddleCenter, null, TipsSizeMode.Large, null, TipsState.Info);
                            var downAwaiter = wsNovel.DownloadNovel(downloadPath, downloadUrl, fileName).GetAwaiter();
                            downAwaiter.OnCompleted(() => {
                                FrmTips.ShowTips(this, "下载完成！", 1000, false, ContentAlignment.MiddleCenter, null, TipsSizeMode.Large, null, TipsState.Success);
                            });
                        }
                    }
                    break;
                default:
                    break;
            }
        }


        ///// <summary>
        ///// 章节列表单击
        ///// </summary>
        ///// <param name="sender"></param>
        ///// <param name="e"></param>
        //private void lvChapters_Click(object sender, EventArgs e)
        //{
        //    if (listviewChapters.SelectedItems.Count <= 0) { return; }

        //    string url = listviewChapters.SelectedItems[0].Tag.ToString();

        //    // 棉花糖
        //    if (url.Contains(mhtNovel.SiteHomeUrl))
        //    {
        //        var mhtAwaiter = mhtNovel.GetChapterContent(url).GetAwaiter();
        //        mhtAwaiter.OnCompleted(() => UiOperate.ShowReadingWindow(this, tabPageReading, panelReading, richTextBoxChapterContent, mhtAwaiter.GetResult()));
        //    }

        //    // 炫书网
        //    if (url.Contains(xswNovel.SiteHomeUrl))
        //    {
        //        var xswAwaiter = xswNovel.GetChapterContent(url).GetAwaiter();
        //        xswAwaiter.OnCompleted(() => UiOperate.ShowReadingWindow(this, tabPageReading, panelReading, richTextBoxChapterContent, xswAwaiter.GetResult()));
        //    }

        //    // 文桑
        //    if (url.Contains(wsNovel.SiteHomeUrl))
        //    {
        //        var wsAwaiter = wsNovel.GetChapterContent(url).GetAwaiter();
        //        wsAwaiter.OnCompleted(()=> UiOperate.ShowReadingWindow(this, tabPageReading, panelReading, richTextBoxChapterContent, wsAwaiter.GetResult()));
        //    }
        //}


        /// <summary>
        /// 章节被单击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvChapterList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvChapterList.SelectedCells.Count <= 0)
            {
                return;
            }
            string url = dgvChapterList.SelectedCells[0].Tag?.ToString();
            if (url == null)
            {
                return;
            }
            // 获取并阅读章节
            GetAndReadChapter(url);
        }




        /// <summary>
        /// 显示阅读面板
        /// </summary>
        /// <param name="contentStr"></param>
        private void ShowReadingWindow(string contentStr)
        {
            Action action = () =>
            {
                panelReading.Width = tabPageReading.Width;
                richTextBoxChapterContent.Font = new Font("宋体", 12);
                richTextBoxChapterContent.BackColor = Color.Honeydew;
                richTextBoxChapterContent.Text = contentStr;
                panelReading.Visible = true;
            };
            this.BeginInvoke(action);
        }


        /// <summary>
        /// 关闭阅读面板
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            richTextBoxChapterContent.Clear();
            panelReading.Visible = false;
        }


        /// <summary>
        /// 上一章
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnPreviousChapter_Click(object sender, EventArgs e)
        {
            int selectedRowIndex = dgvChapterList.SelectedCells[0].RowIndex; //选中行索引
            int selectedColIndex = dgvChapterList.SelectedCells[0].ColumnIndex; //选中列索引
            // Console.WriteLine("selectedRowIndex: "+selectedRowIndex);
            // Console.WriteLine("selectedColIndex: " + selectedColIndex);
            if (selectedRowIndex == 0 && selectedColIndex == 0)
            {
                FrmTips.ShowTips(this, "已到头！", 1000, false, ContentAlignment.MiddleCenter, null, TipsSizeMode.Large, null, TipsState.Info);
                return;
            }
            int ri;
            int ci;
            string url;
            switch (selectedColIndex)
            {
                case 0:
                    ri = selectedRowIndex - 1;
                    ci = 1;
                    // Console.WriteLine("row index: " + ri);
                    // Console.WriteLine("cell index: " + ci);
                    url = dgvChapterList.Rows[ri].Cells[ci].Tag?.ToString();
                    if (url == null)
                    {
                        return;
                    }
                    // Console.WriteLine(url);
                    dgvChapterList.CurrentCell = dgvChapterList.Rows[ri].Cells[ci];
                    dgvChapterList.CurrentCell.Selected = true;

                    // 获取并阅读章节
                    GetAndReadChapter(url);

                    break;
                case 1:
                    ri = selectedRowIndex;
                    ci = 0;
                    // Console.WriteLine("row index: " + ri);
                    // Console.WriteLine("cell index: " + ci);
                    url = dgvChapterList.Rows[ri].Cells[ci].Tag?.ToString();
                    if (url == null)
                    {
                        return;
                    }
                    // Console.WriteLine(url);
                    dgvChapterList.CurrentCell = dgvChapterList.Rows[ri].Cells[ci];
                    dgvChapterList.CurrentCell.Selected = true;

                    // 获取并阅读章节
                    GetAndReadChapter(url);

                    break;
                default:
                    break;
            }
        }


        /// <summary>
        /// 下一章
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnNextChapter_Click(object sender, EventArgs e)
        {
            int selectedRowIndex = dgvChapterList.SelectedCells[0].RowIndex; //选中行索引
            int selectedColIndex = dgvChapterList.SelectedCells[0].ColumnIndex; //选中列索引
            int ri;
            int ci;
            string url;
            switch (selectedColIndex)
            {
                case 0:
                    ri = selectedRowIndex;
                    ci = 1;
                    url = dgvChapterList.Rows[ri].Cells[ci].Tag?.ToString();
                    if (url == null)
                    {
                        FrmTips.ShowTips(this, "已读完！", 1000, false, ContentAlignment.MiddleCenter, null, TipsSizeMode.Large, null, TipsState.Info);
                        return;
                    }
                    dgvChapterList.CurrentCell = dgvChapterList.Rows[ri].Cells[ci];
                    dgvChapterList.CurrentCell.Selected = true;

                    // 获取并阅读章节
                    GetAndReadChapter(url);

                    break;
                case 1:
                    ri = selectedRowIndex + 1;
                    ci = 0;
                    if (ri >= dgvChapterList.RowCount)
                    {
                        FrmTips.ShowTips(this, "已读完！", 1000, false, ContentAlignment.MiddleCenter, null, TipsSizeMode.Large, null, TipsState.Info);
                        return;
                    }
                    url = dgvChapterList.Rows[ri].Cells[ci].Tag?.ToString();
                    if (url == null)
                    {
                        FrmTips.ShowTips(this, "已读完！", 1000, false, ContentAlignment.MiddleCenter, null, TipsSizeMode.Large, null, TipsState.Info);
                        return;
                    }
                    dgvChapterList.CurrentCell = dgvChapterList.Rows[ri].Cells[ci];
                    dgvChapterList.CurrentCell.Selected = true;

                    // 获取并阅读章节
                    GetAndReadChapter(url);

                    break;
                default:
                    break;
            }

        }


        /// <summary>
        /// 更换阅读框文本内容
        /// </summary>
        /// <param name="contentStr"></param>
        private void ChangeReadingWords(string contentStr)
        {
            Action action = () =>
            {
                richTextBoxChapterContent.Text = contentStr;
            };
            this.BeginInvoke(action);
        }



        /// <summary>
        /// 获取并阅读章节
        /// </summary>
        /// <param name="url">章节url</param>
        private void GetAndReadChapter(string url)
        {
            // 棉花糖
            if (url.Contains(mhtNovel.SiteHomeUrl))
            {
                var mhtAwaiter = mhtNovel.GetChapterContent(url).GetAwaiter();
                mhtAwaiter.OnCompleted(() => ShowReadingWindow(mhtAwaiter.GetResult()));
            }

            // 炫书网
            if (url.Contains(xswNovel.SiteHomeUrl))
            {
                var xswAwaiter = xswNovel.GetChapterContent(url).GetAwaiter();
                xswAwaiter.OnCompleted(() => ShowReadingWindow(xswAwaiter.GetResult()));
            }

            // 文桑
            if (url.Contains(wsNovel.SiteHomeUrl))
            {
                var wsAwaiter = wsNovel.GetChapterContent(url).GetAwaiter();
                wsAwaiter.OnCompleted(() => ShowReadingWindow(wsAwaiter.GetResult()));
            }
        }
    }
}
